from prowo import Prowo
import json
import socket
import time


def recvfile(s, filename, name):
    print("server ready, now client recv file~~!")
    (file, type) = filename.split('.')
    f = open(name + '.' + type, 'wb')
    while True:
        data = s.recv(4096).decode()
        if data == 'EOF':
            print("recv file success")
            break
        f.write(data)
    f.close()


def sendfile(s, filename):
    print("server ready, now client sending file ~~")
    f = open(filename, 'rb')
    while True:
        data = f.read(4096)
        if not data:
            break
        s.sendall(data)
    f.close()
    time.sleep(1)
    s.sendall('EOF'.encode())
    print("send success!")


def confirm(s, client_command):
    s.send(client_command.encode())
    data = s.recv(4096).decode()
    if data == 'ready':
        return True


def uploadFile(ip, port, filename):
    action = 'put'
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_command = action + ' ' + filename
    s.connect((ip, port))
    if action == 'put':
        if confirm(s, client_command):
            sendfile(s, filename)
        else:
            print("server get error")
    else:
        print("command error!")
    s.close()


if __name__ == "__main__":
    ip = '192.168.12.1'
    port = 9666
    filename = 'app.py'
    uploadFile(ip, port, filename)

    p = Prowo(ip, '22224', 'host')
    msg = {'name': filename}
    jmsg1 = json.dumps(msg)
    p.socketClient(ip, 22224, jmsg1)
